use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::process::Command;

fn main() -> io::Result<()> {
    let args: Vec<String> = env::args().collect();
    if args.len() < 3 {
        eprintln!("Usage: tts_reader <file_path> <start_line>");
        std::process::exit(1);
    }

    let path = &args[1];
    let start_line: usize = match args[2].parse() {
        Ok(num) => num,
        Err(_) => {
            eprintln!("Parameter 2 must be a positive integer.");
            std::process::exit(1);
        }
    };

    // Read settings from tts_setting.txt if it exists
    let mut rate = String::new();
    let mut pitch = String::new();
    if let Ok(file) = File::open("tts_setting.txt") {
        for line in BufReader::new(file).lines() {
            let line = line?;
            let parts: Vec<&str> = line.split(':').collect();
            if parts.len() == 2 {
                match parts[0] {
                    "rate" => rate = parts[1].to_string(),
                    "p" => pitch = parts[1].to_string(),
                    _ => eprintln!("Unknown setting in tts_setting.txt: {}", parts[0]),
                }
            }
        }
    }

    // Read and speak the lines from the file
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    for (index, line) in reader.lines().enumerate() {
        let current_line = index + 1;
        let line = line?;
        if current_line >= start_line && !line.trim().is_empty() {
            println!("Reading line {}", current_line);
            let mut cmd = Command::new("termux-tts-speak");
            
            if !rate.is_empty() {
                cmd.arg("-r").arg(&rate);
            }
            if !pitch.is_empty() {
                cmd.arg("-p").arg(&pitch);
            }
            cmd.arg(&line).status()?;
        }
    }

    Ok(())
}
